package com.ruoyi.blog.controller;

import com.ruoyi.blog.domain.BlogArticle;
import com.ruoyi.blog.service.IBlogArticleService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lf on 2020/12/20.
 */
@RestController
@RequestMapping("/blog/article")
public class BlogArticleController extends BaseController {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    @Autowired
    IBlogArticleService articleService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public AjaxResult addNewArticle(BlogArticle article) {
        article.setUid(getUserId());
        int result = articleService.addNewArticle(article);
        if (result == 1) {
            return success(article.getId()+"");
        } else {
            return error(article.getState() == 0 ? "文章保存失败!" : "文章发表失败!");
        }
    }

    /**
     * 上传图片
     *
     * @return 返回值为图片的地址
     */
    @RequestMapping(value = "/uploadimg", method = RequestMethod.POST)
    public AjaxResult uploadImg(HttpServletRequest req, MultipartFile image) {
        StringBuffer url = new StringBuffer();
        String filePath = "/blogimg/" + sdf.format(new Date());
        String imgFolderPath = req.getServletContext().getRealPath(filePath);
        File imgFolder = new File(imgFolderPath);
        if (!imgFolder.exists()) {
            imgFolder.mkdirs();
        }
        url.append(req.getScheme())
                .append("://")
                .append(req.getServerName())
                .append(":")
                .append(req.getServerPort())
                .append(req.getContextPath())
                .append(filePath);
        String imgName = UUID.randomUUID() + "_" + image.getOriginalFilename().replaceAll(" ", "");
        try {
            IOUtils.write(image.getBytes(), new FileOutputStream(new File(imgFolder, imgName)));
            url.append("/").append(imgName);
            return success(url.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return error( "上传失败!");
    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public TableDataInfo getArticleByState(BlogArticle article) {
        startPage();
        List<BlogArticle> articles = articleService.getArticleList(article);
        return getDataTable(articles);
    }

    @RequestMapping(value = "/{aid}", method = RequestMethod.GET)
    public BlogArticle getArticleById(@PathVariable Long aid) {
        return articleService.getArticleById(aid);
    }

    @RequestMapping(value = "/dustbin", method = RequestMethod.PUT)
    public AjaxResult updateArticleState(Long[] aids, Integer state) {
        if (articleService.updateArticleState(aids, state) == aids.length) {
            return success( "删除成功!");
        }
        return error("删除失败!");
    }

    @RequestMapping(value = "/restore", method = RequestMethod.PUT)
    public AjaxResult restoreArticle(Integer articleId) {
        if (articleService.restoreArticle(articleId) == 1) {
            return success("还原成功!");
        }
        return error("还原失败!");
    }

    @RequestMapping("/dataStatistics")
    public Map<String,Object> dataStatistics() {
        Map<String, Object> map = new HashMap<>();
        List<String> categories = articleService.getCategories(getUserId());
        List<Integer> dataStatistics = articleService.getDataStatistics(getUserId());
        map.put("categories", categories);
        map.put("ds", dataStatistics);
        return map;
    }
}
